# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, request, redirect, url_for, jsonify
from web.models.user import User
from common.libs.UserService import UserService
import datetime
from application import db

route_account = Blueprint('account_page', __name__)


@route_account.route("/index")
def index():
    '''查询所有数据'''
    user_list = User.query.all()
    context = {
        "user_list": user_list
    }
    return render_template("account/index.html", **context)


@route_account.route("/info")
def info():
    '''跳转到帐号详情页'''
    # 通过获取账号id，获取账号的详细信息
    # 这里要考虑当获取id，没有的时候两种情况
    user_id = request.values.get("id")
    # 为空，或者小于1的id
    if (not user_id.isdigit()) or (not user_id) or (int(user_id) < 1):
        return redirect(url_for('account_page.index'))  # 反向解析
    user_info = User.query.filter(User.uid == user_id).first()
    # 当该账户不存在时
    if not  user_info:
        return redirect(url_for('account_page.index'))  # 反向解析
    context = {
        "user_info": user_info
    }
    return render_template("account/info.html", **context)


@route_account.route("/set", methods=['GET', 'POST'])
def set():
    """新增或者修改账号"""
    if request.method == "GET":
        # 修改账号信息，通过当前账户id进行修改账户信息
        # 接受一个id参数
        context = {}
        req = request.args
        uid = req.get("id", 0)
        print("要修改的账号id：", uid)
        user_info = None
        if uid:
            user_info = User.query.filter(User.uid==uid).first()
        context["user_info"] = user_info
        return render_template("account/set.html", **context)
    # 以下是post请求执行的代码
    # 1.获取请求参数
    req = request.values
    nickname = req["nickname"] if "nickname" in req else ""
    mobile = req["mobile"] if "mobile" in req else ""
    email = req["email"] if "email" in req else ""
    login_name = req["login_name"] if "login_name" in req else ""
    login_pwd = req["login_pwd"] if "login_pwd" in req else ""
    id = req["id"] if "id" in req else 0
    # 判断是否重名
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    # 验证登录名是否被注册 在添加账号时，User.uid != id才会成立
    has_in = User.query.filter(User.login_name == login_name, User.uid != id).first()
    if has_in:
        resp["code"] = -1
        resp["msg"] = "该登录名已经存在，请换一个试一试 "
        return jsonify(resp)
    # 判断是新增还是修改
    # 修改or添加账号？加入user_info为空，则是新增，不为空，则为修改
    user_info = User.query.filter_by(uid=id).first()
    if user_info:  # user_info不为空，则为修改操作
        # 如果admin账号，不允许修改
        if user_info and user_info.uid == 1:
            resp["code"] = -1
            resp["msg"] = "该用户是admin账号，不允许修改编辑"
            return jsonify(resp)
        model_user = user_info
    else:  # 假设user_info为空，则为新增账号
        # 把合法的新增用户数据提交到数据库中
        model_user = User()  # 新建一个User实例
        model_user.login_salt = UserService.genSalt(16)  # 自动产生一个加盐数据
        model_user.created_time = datetime.datetime.now()
    # 以下代码不管是新增还是修改，共同操作
    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    model_user.updated_time = datetime.datetime.now()
    if login_pwd != '******':  # 表示修改了密码 重新生成密码保存，要结合前端的密码默认值比较
        model_user.login_pwd = UserService.genPwd(login_pwd, model_user.login_salt)
    # 提交到数据库中去
    db.session.add(model_user)
    db.session.commit()

    return jsonify(resp)



@route_account.route('/ops', methods=["GET", "POST"])
def ops():
    '''删除或者回复账号'''
    resp = {
        "code": 200,
        "msg": "操作成功",
        "data": {}
    }
    req = request.values
    act = req["act"] if "act" in req else ""
    id = req["id"] if "id" in req else ""
    print("获取到的数据：", act, id)

    if act not in ["remove", "recover"]:
        resp["code"] = -1
        resp["msg"] = "操作有误"
        return jsonify(resp)
    if not id:
        resp["code"] = -1
        resp["msg"] = "请选择要操作的会员"
        return jsonify(resp)
    user_info = User.query.filter(User.uid==id).first()
    if not user_info:
        resp["code"] = -1
        resp["msg"] = "指定账号不存在"
        return jsonify(resp)
    if user_info and user_info.uid == 1:
        resp["code"] = -1
        resp["msg"] = "该用户是admin账号，不允许修改编辑"
        return jsonify(resp)
    # 软删除-逻辑删除操作
    if act == "remove":
        user_info.status = 0  # 删除状态

    elif act == "recover":  # 变成不删除状态
        user_info.status = 1

    # 软删除，其实就是修改账号的一些属性状态
    user_info.updated_time = datetime.datetime.now()
    db.session.add(user_info)
    db.session.commit()

    return jsonify(resp)






